package cn.xtits.xtp.controller;

import cn.xtits.xtf.common.utils.JsonUtil;
import cn.xtits.xtf.common.web.AjaxResult;
import cn.xtits.xtf.common.web.Pagination;
import cn.xtits.xtp.entity.CodingRule;
import cn.xtits.xtp.entity.Custom;
import cn.xtits.xtp.entity.CustomExample;
import cn.xtits.xtp.enums.CodingRuleEnum;
import cn.xtits.xtp.enums.CodingRuleTypeEnum;
import cn.xtits.xtp.enums.ErrorCodeEnums;
import cn.xtits.xtp.service.CodingRuleService;
import cn.xtits.xtp.service.CustomService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * @fileName: CustomController.java
 * @author: Dan
 * @createDate: 2018-02-28 13:43:14
 * @description: 客户
 */
@RestController
@RequestMapping("/custom")
public class CustomController extends BaseController {

    @Autowired
    private CustomService service;

    @Autowired
    private CodingRuleService codingRuleService;

    @RequiresPermissions("ibasic-custom:insert")
    @RequestMapping(value = "insertCustom")
    public AjaxResult insertCustom(
            @RequestParam(value = "data", required = false) String data) {
        Custom record = JsonUtil.fromJson(data, Custom.class);
        record.setCode(getCode());
        AjaxResult exist = exist(record);
        if (exist != null) {
            return exist;
        }
        //Date dt = getDateNow();
        record.setCreateDate(null);
        record.setMakeBillMan(getUserName());
        record.setModifier(getUserName());
        record.setModifyDate(null);
        record.setDeleteFlag(false);
        service.insert(record);
        return new AjaxResult(record);
    }

    @RequiresPermissions("ibasic-custom:delete")
    @RequestMapping(value = "deleteCustom")
    public AjaxResult deleteCustom(
            @RequestParam(value = "id", required = false) int id) {
        Custom record = new Custom();
        record.setId(id);
        record.setDeleteFlag(true);
        record.setModifier(getUserName());
        record.setModifyDate(null);
        int row = service.updateByPrimaryKeySelective(record);
        return new AjaxResult(row);
    }

    @RequiresPermissions("ibasic-custom:update")
    @RequestMapping(value = "updateCustom")
    public AjaxResult updateCustom(
            @RequestParam(value = "data", required = false) String data) {
        Custom record = JsonUtil.fromJson(data, Custom.class);
        AjaxResult exist = exist(record);
        if (exist != null) {
            return exist;
        }
        record.setCreateDate(null);
        record.setMakeBillMan(null);
        record.setModifyDate(null);
        record.setModifier(getUserName());
        record.setDeleteFlag(false);
        service.updateByPrimaryKeySelective(record);
        return new AjaxResult(record);
    }

    @RequestMapping(value = "listCustom")
    public AjaxResult listCustom(
            @RequestParam(value = "payMode", required = false) String payMode,
            @RequestParam(value = "code", required = false) String code,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "shortName", required = false) String shortName,
            @RequestParam(value = "director", required = false) String director,
            @RequestParam(value = "tel", required = false) String tel,
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "address", required = false) String address,
            @RequestParam(value = "taxId", required = false) String taxId,
            @RequestParam(value = "mail", required = false) String mail,
            @RequestParam(value = "site", required = false) String site,
            @RequestParam(value = "fax", required = false) String fax,
            @RequestParam(value = "remark", required = false) String remark,
            @RequestParam(value = "operatorId", required = false) Integer operatorId,
            @RequestParam(value = "operatorName", required = false) String operatorName,
            @RequestParam(value = "salesManId", required = false) Integer salesManId,
            @RequestParam(value = "salesManName", required = false) String salesManName,
            @RequestParam(value = "areaId", required = false) Integer areaId,
            @RequestParam(value = "areaCode", required = false) String areaCode,
            @RequestParam(value = "areaName", required = false) String areaName,
            @RequestParam(value = "payDay", required = false) Integer payDay,
            @RequestParam(value = "post", required = false) String post,
            @RequestParam(value = "pageSize", required = false) Integer pageSize,
            @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
            @RequestParam(value = "orderBy", required = false) String orderBy,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate) {

        DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
        CustomExample example = new CustomExample();
        example.setPageIndex(pageIndex);
        example.setPageSize(pageSize);
        if (StringUtils.isNotBlank(orderBy)) {
            example.setOrderByClause(orderBy);
        }
        CustomExample.Criteria criteria = example.createCriteria();
        criteria.andDeleteFlagEqualTo(false);

        if (StringUtils.isNotBlank(payMode)) {
            criteria.andPayModeEqualTo(payMode);
        }
        if (StringUtils.isNotBlank(operatorName)) {
            criteria.andOperatorNameLike(operatorName);
        }
        if (StringUtils.isNotBlank(salesManName)) {
            criteria.andSalesManNameLike(salesManName);
        }
        if (StringUtils.isNotBlank(code)) {
            criteria.andCodeLike(code);
        }
        if (StringUtils.isNotBlank(name)) {
            criteria.andNameLike(name);
        }
        if (StringUtils.isNotBlank(shortName)) {
            criteria.andShortNameLike(shortName);
        }
        if (StringUtils.isNotBlank(director)) {
            criteria.andDirectorLike(director);
        }
        if (StringUtils.isNotBlank(tel)) {
            criteria.andTelLike(tel);
        }
        if (StringUtils.isNotBlank(phone)) {
            criteria.andPhoneLike(phone);
        }
        if (StringUtils.isNotBlank(address)) {
            criteria.andAddressLike(address);
        }
        if (StringUtils.isNotBlank(taxId)) {
            criteria.andTaxIdLike(taxId);
        }
        if (StringUtils.isNotBlank(mail)) {
            criteria.andMailLike(mail);
        }
        if (StringUtils.isNotBlank(site)) {
            criteria.andSiteLike(site);
        }
        if (StringUtils.isNotBlank(fax)) {
            criteria.andFaxLike(fax);
        }
        if (StringUtils.isNotBlank(remark)) {
            criteria.andRemarkLike(remark);
        }
        if (StringUtils.isNotBlank(startDate)) {
            criteria.andCreateDateGreaterThanOrEqualTo(DateTime.parse(startDate, format).toDate());
        }
        if (StringUtils.isNotBlank(endDate)) {

            criteria.andCreateDateLessThanOrEqualTo(DateTime.parse(endDate, format).toDate());
        }
        if (operatorId != null) {
            criteria.andOperatorIdEqualTo(operatorId);
        }
        if (salesManId != null) {
            criteria.andSalesManIdEqualTo(salesManId);
        }
        if (areaId != null) {
            criteria.andAreaIdEqualTo(areaId);
        }
        if (StringUtils.isNotBlank(areaCode)) {
            criteria.andAreaCodeLike(areaCode);
        }
        if (StringUtils.isNotBlank(areaName)) {
            criteria.andAreaNameLike(areaName);
        }
        if (payDay != null) {
            criteria.andPayDayEqualTo(payDay);
        }
        if (StringUtils.isNotBlank(post)) {
            criteria.andPostLike(post);
        }

        List<Custom> list = service.listByExample(example);
        Pagination<Custom> pList = new Pagination<>(example, list, example.getCount());
        return new AjaxResult(pList);
    }

    @RequestMapping(value = "getCustom")
    public AjaxResult getCustom(@RequestParam(value = "id", required = false) Integer id) {
        Custom res = service.getByPrimaryKey(id);
        return new AjaxResult(res);
    }

    private String getCode() {
        Map<String, Object> assemblyCodingMap = codingRuleService.getAssemblyCoding(CodingRuleEnum.CUSTOM_CODE.key);
        StringBuffer codeBuffer = new StringBuffer();
        //固定字段
        if (assemblyCodingMap.containsKey(CodingRuleTypeEnum.FIXED_FIELD.key)) {
            codeBuffer.append(assemblyCodingMap.get(CodingRuleTypeEnum.FIXED_FIELD.key).toString());
        }
        //时间字段
        if (assemblyCodingMap.containsKey(CodingRuleTypeEnum.DATE_FIELD.key)) {
            codeBuffer.append(DateTime.now().toString(assemblyCodingMap.get(CodingRuleTypeEnum.DATE_FIELD.key).toString()));
        }
        CodingRule codingRule = null;
        //自增字段
        if (assemblyCodingMap.containsKey(CodingRuleTypeEnum.IDENTITY_FIELD.key)) {
            codingRule = (CodingRule) assemblyCodingMap.get(CodingRuleTypeEnum.IDENTITY_FIELD.key);
        }
        String codeLike = codeBuffer.toString();
        CustomExample example = new CustomExample();
        example.setPageSize(1);
        example.setOrderByClause("Code desc, Id desc");
        CustomExample.Criteria exampleCriteria = example.createCriteria();
        exampleCriteria.andCodeLike(codeLike + "%");
        List<Custom> customList = service.listByExample(example);
        if (codingRule != null) {
            int length = codingRule.getLength() == null ? 4 : codingRule.getLength();
            long initValue = Long.parseLong(codingRule.getInitValue() == null ? "1" : codingRule.getInitValue());
            if (customList.size() > 0) {
                String code = customList.get(0).getCode();

                String substring = code.substring(codeLike.length(), code.length());

                initValue = Long.parseLong(substring) + 1;
            }
            String format = String.format("%0" + length + "d", initValue);
            return codeLike + format;
        }
        return codeLike;
    }

    private AjaxResult exist(Custom entity) {
        {
            CustomExample example = new CustomExample();
            example.setPageSize(1);
            CustomExample.Criteria criteria = example.createCriteria();
            criteria.andDeleteFlagEqualTo(false);
            if (entity.getId() != null && entity.getId() > 0) {
                criteria.andIdNotEqualTo(entity.getId());
            }
            criteria.andCodeEqualTo(entity.getCode());
            if (service.listByExample(example).size() > 0) {
                return new AjaxResult(ErrorCodeEnums.RECORD_EXISTS.value, "编码：" + entity.getCode() + ",已存在!");
            }
        }
        {
            CustomExample example = new CustomExample();
            example.setPageSize(1);
            CustomExample.Criteria criteria = example.createCriteria();
            criteria.andDeleteFlagEqualTo(false);
            if (entity.getId() != null && entity.getId() > 0) {
                criteria.andIdNotEqualTo(entity.getId());
            }
            criteria.andNameEqualTo(entity.getName());
            if (service.listByExample(example).size() > 0) {
                return new AjaxResult(ErrorCodeEnums.RECORD_EXISTS.value, "名称：" + entity.getName() + ",已存在!");
            }
        }
        return null;

    }

}